package com.synergy.stockflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.synergy.stockflow.constant.ResultCode;
import com.synergy.stockflow.entity.SysRolePerm;
import com.synergy.stockflow.exception.BusinessException;
import com.synergy.stockflow.mapper.SysRolePermMapper;
import com.synergy.stockflow.service.SysRolePermService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

@Service
@Transactional
public class SysRolePermServiceImpl extends ServiceImpl<SysRolePermMapper, SysRolePerm> implements SysRolePermService {
    @Override
    public boolean save(SysRolePerm entity) {
        LambdaQueryWrapper<SysRolePerm> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRolePerm::getSysRoleId, entity.getSysRoleId());
        queryWrapper.eq(SysRolePerm::getSysPermissionId, entity.getSysPermissionId());
        List<SysRolePerm> sysRolePerms = baseMapper.selectList(queryWrapper);
        if (sysRolePerms != null && !sysRolePerms.isEmpty()) {
            throw new BusinessException(ResultCode.BUSINESS_EXCEPTION, "角色存在当前权限");
        }
        return super.save(entity);
    }

    @Override
    public boolean saveBatch(Collection<SysRolePerm> entityList, int batchSize) {
        if (entityList == null || entityList.isEmpty()) {
            return true;
        }
        Iterator<SysRolePerm> it = entityList.iterator();
        Integer roleId = it.next().getSysRoleId();

        while (it.hasNext()) {
            if (!it.next().getSysRoleId().equals(roleId)) {
                throw new IllegalArgumentException("权限列表包含多个角色ID，不支持批量跨角色更新");
            }
        }
        LambdaQueryWrapper<SysRolePerm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRolePerm::getSysRoleId, roleId);
        this.remove(wrapper);

        return super.saveBatch(entityList, batchSize);
    }
}
